import React, { useState, forwardRef } from "react";

interface MyInputProps {
  type?: string;
  className?: string;
  value?: string;
  placeholder?: string;
  handleChange?: (e: React.ChangeEvent<HTMLInputElement>) => void;
  MyOnkeydown?:(e: React.KeyboardEvent<HTMLInputElement>) => void;
  required?: boolean;
  requiredMessage?: string;
  minLength?: number;
  minLengthMessage?: string;
  maxLength?: number;
  maxLengthMessage?: string;
  pattern?: RegExp;
  patternMessage?: string;
}

interface MyInputRef {
  validate: () => boolean;
}

const MyInput = forwardRef<MyInputRef, MyInputProps>(
  ({
    type = "text",
    className,
    value,
    placeholder,
    handleChange,
    MyOnkeydown,
    required = false,
    requiredMessage = "此项为必填项",
    minLength,
    minLengthMessage = `至少需要 ${minLength} 个字符`,
    maxLength,
    maxLengthMessage = `最多允许 ${maxLength} 个字符`,
    pattern,
    patternMessage = "输入格式不正确",
  }) =>
    // ref
    {
      const [error, setError] = useState<string>("");

      const validate = (value: string): boolean => {
        if (required && !value) {
          setError(requiredMessage);
          return false;
        }
        if (minLength && value && value.length < minLength) {
          setError(minLengthMessage);
          return false;
        }
        if (maxLength && value && value.length > maxLength) {
          setError(maxLengthMessage);
          return false;
        }
        if (pattern && value && !pattern.test(value)) {
          setError(patternMessage);
          return false;
        }
        setError("");
        return true;
      };

      // // 暴露 validate 方法给父组件
      // useImperativeHandle(ref, () => ({
      //   validate,
      // }));

      const onValueChange = (e: React.ChangeEvent<HTMLInputElement>) => {
        const value = e.target.value;
        console.log(value, "value");

        validate(value);
        if (handleChange) {
          handleChange(e);
        }
      };

      return (
        <>
          <input
            type={type}
            className={className}
            value={value}
            placeholder={placeholder}
            onChange={onValueChange}
            required={required}
            onKeyDown={MyOnkeydown}
          />
          {error && (
            <div style={{ color: "red", fontSize: "12px" }}>{error}</div>
          )}
        </>
      );
    }
);

export default MyInput;
